<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      div {
        position: relative;
      }
      p {
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div style="width: 400px; height: 400px; background: pink">
      <p style="width: 50px; height: 50px; background: peru"></p>
      <script>
        document.onkeydown = function (e) {
          var e = e || window.e;
          var pEle = document.querySelector("p");
          var boxX = parseInt(pEle.offsetLeft);
          var boxY = parseInt(pEle.offsetTop);
          console.log(e.key);
            if (boxX >= 0) {
              if (e.key == "ArrowRight") {
                var pEle = document.querySelector("p");
                boxX = parseInt(pEle.offsetLeft);
                boxX += 50;
                pEle.style.left = `${boxX}px`;
              }
              if (e.key == "ArrowLeft") {
                var pEle = document.querySelector("p");
                boxX = parseInt(pEle.offsetLeft);
                boxX -= 50;
                pEle.style.left = `${boxX}px`;
              }
            }
            if (boxY >= 0) {
              if (e.key == "ArrowUp") {
                var pEle = document.querySelector("p");
                boxY = parseInt(pEle.offsetTop);
                boxY -= 50;
                boxY -= 50;
                boxY -= 50;
                pEle.style.top = `${boxY}px`;
              }
              if (e.key == "ArrowDown") {
                var pEle = document.querySelector("p");
                console.log(pEle.offsetTop);
                boxY = parseInt(pEle.offsetTop);
                boxY += 50;
                pEle.style.top = `${boxY}px`;
              }
            }
        };
      </script>
    </div>
  </body>
</html>
